package com.zhongya.example.view

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class ShimmerTextView : AppCompatTextView {

    var mDx = 0f

    lateinit var mPaint : Paint
    lateinit var mLinearGradient : LinearGradient

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        mPaint = paint

        val length = mPaint.measureText(text.toString())

        createAnim(length)
        createLinearGradient(length)

    }

    override fun onDraw(canvas: Canvas?) {
        val matrix = Matrix()
        matrix.setTranslate(mDx,0f)
        mLinearGradient.setLocalMatrix(matrix)
        mPaint.shader = mLinearGradient

        super.onDraw(canvas)
    }


    private fun createAnim(length: Float) {
        val animator = ValueAnimator.ofFloat(0f,2*length)
        animator.addUpdateListener {
            mDx = it.animatedValue as Float
            postInvalidate()
        }
        animator.repeatMode = ValueAnimator.RESTART
        animator.repeatCount = ValueAnimator.INFINITE
        animator.duration = 2000
        animator.start()
    }

    private fun createLinearGradient(length: Float) {
        mLinearGradient =
            LinearGradient(
                -length,
                0f,
                0f,
                0f,
                intArrayOf(currentTextColor,0xff00ff00.toInt(),currentTextColor),
//                intArrayOf(0xffff0000.toInt(), 0xff00ff00.toInt(), 0xffff0000.toInt()),
                floatArrayOf(0f,0.5f,1f),
                Shader.TileMode.CLAMP
            )

    }


}